package com.mofang.powerdekorhelper.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;

import com.mofang.powerdekorhelper.R;
import com.mofang.powerdekorhelper.activity.activity.ProcessActivity;
import com.mofang.powerdekorhelper.activity.news.NewsInfoDetialActivity;
import com.mofang.powerdekorhelper.base.BaseActivity;
import com.mofang.powerdekorhelper.fragment.ActivityFragment;
import com.mofang.powerdekorhelper.fragment.PersonalCenterFragment;
import com.mofang.powerdekorhelper.fragment.WorkPlantFragment;
import com.mofang.powerdekorhelper.service.DialogService;
import com.mofang.powerdekorhelper.utils.DialogUtils;
import com.mofang.powerdekorhelper.utils.GetPermisionUtils;
import com.mofang.powerdekorhelper.utils.L;
import com.mofang.powerdekorhelper.utils.SharePerforenceUtils;
import com.mofang.powerdekorhelper.utils.T;
import com.mofang.powerdekorhelper.utils.VersionUpdataUtil;
import com.mofang.powerdekorhelper.witget.TitleBar;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.mofang.powerdekorhelper.utils.GetPermisionUtils.PERMISSON_REQUESTCODE;

/**
 * 主Activity，包含三个Fragment
 * 审核账号
 * 组织号：037110
 * 部门号：ZZA104
 * 账号：17739782107
 * 密码：123456
 */

public class MainActivity extends BaseActivity {

    @BindView(R.id.main_titlebar)
    TitleBar mTitleBar;

    public static final int QRCODE_REQUEST_CODE = 666;

    private ActivityFragment activityFragment;
    private WorkPlantFragment workpFragment;
    private PersonalCenterFragment personalFragment;
    private DialogUtils dialogUtils;
    private GetPermisionUtils getPermisionUtils;

    @Override
    public void initView() {
        inflateLayout(R.layout.activity_main_layout);
        initTitleBar(R.string.activity_list);
     /*   RefWatcher refWatcher = BaseApplication.getRefWatcher();
        refWatcher.watch(this);*/
    }

    @Override
    public void initData() {

        setSelect(0);
        // 获取权限
        String[] needPermissions = {
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,//存储卡写入权限
                Manifest.permission.READ_EXTERNAL_STORAGE,//存储卡读取权限
                Manifest.permission.READ_PHONE_STATE,//读取手机状态权限
                Manifest.permission.ACCESS_FINE_LOCATION
        };

        getPermisionUtils = new GetPermisionUtils(this);
        getPermisionUtils.checkPermissions(needPermissions);

        // 版本检测
        new VersionUpdataUtil(MainActivity.this, 1).checkVersion();

        String launchIntent = getIntent().getStringExtra("LaunchIntent");
        String articleId = getIntent().getStringExtra("ArticleId");

        if (launchIntent != null && !launchIntent.equals("")) {
            startActivity(new Intent(this, NewsInfoDetialActivity.class)
                    .putExtra("ArticleId", articleId));
        }
    }

    @OnClick({R.id.tab_column_center_rb, R.id.tab_work_plant_rb, R.id.tab_personal_center_rb})
    void onclick(View v) {
        switch (v.getId()) {

            case R.id.tab_column_center_rb:

                // 栏目中心
                setSelect(0);
                break;
            case R.id.tab_work_plant_rb:

                // 工作台
                setSelect(1);
                break;
            case R.id.tab_personal_center_rb:

                // 我的
                setSelect(2);
                break;
        }
    }

    /**
     * 切换Fragment
     *
     * @param i
     */
    private void setSelect(int i) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        hideFragment(transaction);
        switch (i) {
            case 0:
                if (activityFragment == null) {
                    activityFragment = new ActivityFragment();
                    transaction.add(R.id.fragment_continer, activityFragment);
                }
                transaction.show(activityFragment);
                initTitleBar(R.string.activity_list);

                break;
            case 1:
                if (workpFragment == null) {
                    workpFragment = new WorkPlantFragment();
                    transaction.add(R.id.fragment_continer, workpFragment);
                }
                transaction.show(workpFragment);
                initTitleBar(R.string.work_plant_str);

                break;
            case 2:
                if (personalFragment == null) {
                    personalFragment = new PersonalCenterFragment();
                    transaction.add(R.id.fragment_continer, personalFragment);
                }
                transaction.show(personalFragment);
                initTitleBar(R.string.personal_center_str);

                break;
        }
        transaction.commit();
    }

    private void hideFragment(FragmentTransaction transaction) {
        if (activityFragment != null) {
            transaction.hide(activityFragment);
        }
        if (workpFragment != null) {
            transaction.hide(workpFragment);
        }
        if (personalFragment != null) {
            transaction.hide(personalFragment);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] paramArrayOfInt) {

        if (requestCode == PERMISSON_REQUESTCODE) {
            if (!getPermisionUtils.verifyPermissions(paramArrayOfInt)) {
                getPermisionUtils.showMissingPermissionDialog();
            }
        }
    }

    private void initTitleBar(int titleId) {
        initTitleBar(mTitleBar, titleId);
        mTitleBar.setLeftImageResource(R.mipmap.scan_qrcode_icon);
        mTitleBar.setDividerColor(R.color.grey_midle);
        mTitleBar.setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SharePerforenceUtils.getInstance(MainActivity.this).getLogin()) {
                    Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                    startActivityForResult(intent, QRCODE_REQUEST_CODE);
                }
            }
        });
    }

    // 扫码回调
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        L.i("QRCODE_REQUEST_CODE", "------------------->onActivityResult");

        if (requestCode == QRCODE_REQUEST_CODE) {
            L.i("QRCODE_REQUEST_CODE", "------------------->1");
            if (null != data) {
                L.i("QRCODE_REQUEST_CODE", "------------------->2");
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    L.i("QRCODE_REQUEST_CODE", "------------------->bundle == null");
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    L.i("QRCODE_REQUEST_CODE", "解析结果----------------->" + result);

                    Integer activityId = null;
                    Integer customerId = null;
                    String node3Id = null;
                    if (result != null && !result.equals("")) {
                        try {
                            JSONObject jsonResult = new JSONObject(result);
                            activityId = jsonResult.getInt("activityId");
                            customerId = jsonResult.getInt("customerId");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    L.i("QRCODE_REQUEST_CODE", "activityId----------------->" + activityId);
                    L.i("QRCODE_REQUEST_CODE", "customerId----------------->" + customerId);

                    if (activityId != null && customerId != null) {
                        startActivity(new Intent(this, ProcessActivity.class)
                                .putExtra("ActivityId", activityId)
                                .putExtra("CustomerId", customerId));
                    } else {
                        T.showShort(this, "抱歉，二维码无效");
                    }

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    //toast("解析二维码失败");
                    L.i("QRCODE_REQUEST_CODE", "解析二维码失败----------------->");
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityFragment.fragment = null;
        WorkPlantFragment.fragment = null;
        PersonalCenterFragment.fragment = null;

        Intent intent = new Intent(this, DialogService.class);
        this.stopService(intent);
    }
}
